<?php
if(!$_SESSION['memberID']) {
    exit('{"status":"fail","msg":"登录超时请重新登录"}');
}


/**
 * Created by JetBrains PhpStorm.
 * User: cgp
 * Date: 13-4-6
 * Time: 下午12:32
 *
 * 产品操作
 */
//include '/var/www/html/new/module/qkxproject/commom/autoload.php';
include('../common/autoload.php');
include '/var/www/html/new/d/module/link_product/function.php';
include '/var/www/html/new/d/module/link_product/chkPackage.php';
include '/var/www/html/new/d/class/Product.class.php';
include '/var/www/html/new/d/class/Member.php';
include '/var/www/html/new/d/common/errBack.php';
include_once '/var/www/html/new/d/class/PackTicket.class.php';

use \pft\Prod\Product;
use pft\Prod\Ticket;
$ptypeList = array('A','B','C','D','F','G','H');
$action  = $_REQUEST['action'];
$applyid = $_SESSION['memberID'];
$prod = new \pft\Prod\Product($GLOBALS['le']);
$mem = new \pft\Member\MemberAccount($GLOBALS['le']);
$soap = SoapInit::GetSoapInside();
$member = new Member($soap,$applyid);
$applydid = $_SESSION['memberID'];
//print_r($GLOBALS['le']->fetch_assoc());
switch($action) {
    case 'CreateNewProduct' :
        $ptype = !in_array($_POST['ptype'],$ptypeList) ? Response('{"res":0,"msg":"类型不对！"}'):$_POST['ptype'];
        $sData['title'] = p_match($_POST['mainTitle']) ?
            Response('{"res":0,"msg":"景区名称含有非法字符"}') : safetxt($_POST['mainTitle']);
        if(mb_strlen($sData['title'],'utf8')>20){
            Response('{"res":0,"msg":"景区名称不能超过 30 个字符"}');
        }
        $sData['apply_did'] = abs($_POST['applydid']);
        $byadmin = $_POST['admin']=='16u' ? true : false;
        $parent_id = 0;
        if(ctype_digit($_POST['parent_id']) && $_POST['parent_id']>0) {
            $parent_id = $_POST['parent_id'];
        }
        $tel = trim($_POST['mainPhoneNum']);
        if(strlen($tel)) {
            $sData['tel'] = isphone($tel)||ismobile($tel) ? $tel
                : Response('{"res":0,"msg":"联系电话格式不正确"}');
        }
        if(!empty($_POST['smsMsgPhone'])) {
            $sData['fax'] = ismobile($_POST['smsMsgPhone']) ? $_POST['smsMsgPhone']
                : Response('{"res":0,"msg":"手机号码格式不正确"}');
        }
        if(!empty($_POST['topic'])){
            $topic = $_POST['topic'];
            if(is_array($_POST['topic']))
                $topic = implode(',',$_POST['topic']);
            $sData['topic'] = addslashes(strip_tags($topic));
        }elseif($_POST['resourceID']){
            Response('{"res":0,"msg":"请输入景区主题"}');
        }else{
            $sData['topic'] = '';
        }

        $sData['custom_made'] = $_POST['custom']; // 私人定制
        $sData['px'] = intval($_POST['px']);
        if($sData['px']>30000 && $_SESSION['account']!='123997')//非云游 热门值不能高于30000
            Response('{"res":0,"msg":"热门度不能大于30000"}');
        $sData['terminal_type'] = intval($_POST['terminal_type']);
        $sData['jtype'] = safetxt($_POST['jtype']);
        $sData['runtime'] = safetxt($_POST['runtime']);//营业时间OR出发时间
        //套票产品属性，非空为套票 格式:二维数组json array(array('pid'=>301,'num'=>1),
        //array('pid'=>302,'num'=>3))
        if(isset($_POST['package_attr'])) {
            $sData['attribute'] = trim($_POST['package_attr']);
        }
        if($_POST['d_province']==""||$_POST['d_city']==""){
            Response('{"res":0,"msg":"请先选择省市"}');
        }

        if(isset($_POST['d_province'])) {
            if(is_string($_POST['d_province'])){
                $area_name = "'".mysql_real_escape_string($_POST['d_province'])."','".mysql_real_escape_string($_POST['d_city'])."'";
                $sql = "select area_name,area_id from uu_area where area_name in($area_name) limit 2";
//                echo $sql;exit;
                $GLOBALS['le']->query($sql);
                while($row=$GLOBALS['le']->fetch_assoc()){
                    $_POST['d_province'] = str_replace($row['area_name'],$row['area_id'],$_POST['d_province']);
                    $_POST['d_city'] = str_replace($row['area_name'],$row['area_id'],$_POST['d_city']);
                }
            }
            $sData['area']  = abs($_POST['d_province']) .'|'
                . abs($_POST['d_city']) .'|' .abs($_POST['d_zone']);
        }
        $code=$sData['area'];
        $s_code=explode('|',$code);
        if($s_code[0]==1||$s_code[0]==2||$s_code[0]==3||$s_code[0]==4||$s_code[0]==32||$s_code[0]==33 ||$s_code[0]==34){//32 香港 33 澳门 34 台湾
            $code=$s_code[0].'|1|0';
        }

        //旧版延迟验证会传delaytime=1 如果没选延迟验证 那么delaytime=0
        //新版没有传delaytime这个字段 所以是false
        if(($_POST['delaytime']==1 && (trim($_POST['vtimehour']) || trim($_POST['vtimeminu']))) || ((trim($_POST['vtimehour']) || trim($_POST['vtimeminu'])) && $_POST['delaytime']===null)) {
            $sData['delaytime']  = abs($_POST['vtimehour']) .'|'
                . abs($_POST['vtimeminu']);
        }
        else $sData['delaytime']=null;

        if(isset($_POST['mainAddress'])) {
            $sData['address'] = p_match($_POST['mainAddress'])
                ? Response('{"res":0,"msg":"地址含有非法字符","address":"'.$_POST['mainAddress'].'"}')
                : safetxt($_POST['mainAddress']);
        }elseif($_POST['resourceID']){
            Response('{"res":0,"msg":"请输入景区地址"}');
        }elseif(isset($_POST['start_place'])) {
            //线路产品将出发地、目的地存在runtime字段
            $sData['runtime'] = safetxt($_POST['start_place']) . '|' . safetxt($_POST['end_place']);
        }
        if(is_array($_POST['topic'])){
            if(mb_strlen(end($_POST['topic']),'utf8')>6){
                Response('{"res":0,"msg":"自定义主题不能超过 6 个字符"}');
            }
            if(p_match(end($_POST['topic']))) {
                Response('{"res":0,"msg":"自定义主题含有非法字符！添加失败！"}');
            }
        }
        if(is_string($topic)){
            $topic = explode(',',$topic);
            foreach($topic as $v)
                if(mb_strlen($v,'utf8')>6)
                    Response('{"res":0,"msg":"主题不能超过 6 个字符"}');
        }

        $sData['p_type'] = $ptype;
        //exit;
        $sData['jdjj'] = safetxt($_POST['infoIntro']);
        if(strlen($_POST['detailInfo'])>0) {
            $sData['bhjq'] = safehtml($_POST['detailInfo']);
            if(fliter_words($sData['bhjq'])) {
                Response('{"res":0,"msg":"'.$FieldList[$ptype]['bhjq']['t'].'含有非法字符！添加失败！"}');
            }
        }else{
            $sData['bhjq'] = '';
        }

        if(!empty($_POST['buyTips']) ) {
            if(fliter_words($_POST['buyTips'])) {
                Response('{"res":0,"msg":"'.$FieldList[$ptype]['jqts']['t'].'含有非法字符！添加失败！"}');
            }
            $sData['jqts'] = safetxt($_POST['buyTips']);
        }
        if(!empty($_POST['trafficInfo'])) {
            if(fliter_words($_POST['trafficInfo'])) {
                Response('{"res":0,"msg":"'.$FieldList[$ptype]['jtzn']['t'].'含有非法字符,添加失败！"}');
            }
            $sData['jtzn'] =safetxt($_POST['trafficInfo']);
        }
        if(is_array($_POST['thumb_img'])){
            $_POST['thumb_img'] = array_filter($_POST['thumb_img']);
            if(count($_POST['thumb_img'])){

                $sData['imgpathGrp'] = serialize($_POST['thumb_img']);
                $sData['imgpath'] = $_POST['thumb_img'][0];
            }else{
                Response('{"res":0,"msg":"请上传产品缩略图！"}');
            }

        }else{
            if(empty($_POST['thumb_img'])) {
                Response('{"res":0,"msg":"请上传产品缩略图！"}');
            }else {
                $sData['imgpath'] = $_POST['thumb_img'];
            }
        }
//    elseif(fliter_words($_POST['thumb_img'])) {
//        exit('{"res":0,"msg":"缩略图地址不正确"}');
//    }
        // 经纬度信息
        if(isset( $_POST['end_place_tude'])){
            // $sData['lng_lat_pos'] = $_POST['start_place_tude'].'|'.$_POST['end_place_tude'];
            $sData['lng_lat_pos'] = $_POST['end_place_tude'];
        }elseif($_POST['resource_id']){
            Response('{"res":0,"msg":"请输入经纬度信息"}');
        }
        // 演出类场馆ID
        if($ptype=='H'){
            $sData['venus_id'] = $_POST['venue_id']+0;
            if($sData['venus_id']==0) exit('{"res":0,"msg":"请关联演出场馆"}');
        }

        //添加区域代码
        $sql="select n_code from pft_area_code_concat where s_code='$code' limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $sData['areacode'] = $GLOBALS['le']->f('n_code');

        //关联资源库
        $sData['resourceID'] = $_POST['resource_id']+0;
        if( !empty($_POST['lastid']) && abs($_POST['lastid'])>0 ) {
            $lastid = abs($_POST['lastid']);
            $res = $prod->UpdateScenery($sData, $lastid, $sData['delaytime']);

            // 演出类更改了关联场馆ID
            if($res['errcode']==1000 && $ptype=='H' && $_POST['venue_old']!=$sData['venus_id']){
                $sql = "update uu_land_f set zone_id=0 where lid={$_POST['lastid']}";
                $GLOBALS['le']->query($sql);
            }
        }
        else {
            $now = date('Y-m-d H:i:s');
            if($byadmin ) {
                $sData['passtime'] = $now;
                $sData['status'] = 1;
            }
            $sData['addtime'] = $now;
            $res = $prod->AddProduct($sData, $mem, $parent_id, $sData['delaytime']);
        }

        if($byadmin) $res['byadmin'] = 1;

        Response(json_encode($res));
        break;
    case 'CreateNewTicket':

        $lid = abs($_POST['lastid']) >0 ? abs($_POST['lastid']):Response('{"res":0,"msg":"请先保存景区信息后再保存门票信息！"}');
        $applyid = abs($_POST['did']);
        $tid = $_POST['tid']>0 ? abs($_POST['tid']): 0;// 门票表主键，更新用
        //
        // 先验证价格防止出现多套票门票
        if(count($_POST['ticket'])){
            foreach($_POST['ticket'] as $key=>$post) {
                if($post['pl'] < $post['pg']) Response('{"errcode":1007,"msg":"零售价不能小于供货价！"}');
                if ($post['pg'] >= 10000 || $post['pl'] >= 10000 || $post['price1'] >= 10000) {
                    Response('{"errcode":1008,"msg":"价格配置必须在10000以内！"}');
                }
            }
        }


        if($tid>0){// 修改前日志原数据防止争议
            $sql = "select * from uu_jq_ticket t left join uu_products p on t.pid=p.id where t.id=$tid limit 1";
            $GLOBALS['le']->query($sql);
            if(($p_info = $GLOBALS['le']->fetch_assoc())){
                $p_info['memberID'] = $_SESSION['memberID'];
                write_logs(json_encode($p_info).json_encode($_REQUEST));
            }
        }

        $tobj = new TicketC;
        $res = $tobj->AddTicket($lid,$applyid,$tid, $prod);
        if($res['errcode']!==1000) Response(json_encode($res));
        if($_POST['pid']>0){
            $pid = $_POST['pid']+0;
            if($_POST['provide2']!=$p_info['p_status']){
                $pst = $_POST['provide2']+0;
                $sql = "update uu_products set p_status=$pst where id=$pid limit 1";
                $GLOBALS['le']->query($sql);
            }
        }

        if(isset($_POST['ticket']) && is_array($_POST['ticket'])) {
            $cre_res = array();
            $upt_res = array();
            $cre_inc = 0;
            $upt_inc = 0;
            $pft_rflex_id = abs($_POST['pft_rflex_id']);
//            $soap2 = $pft_rflex_id >0 ? SoapInit::GetSoapFX() : null;
            $soap2 = null;
            $package = getMainId($_REQUEST['pid'], 2);
            $Price = new Price(-1);
            $hasMd = array();

            foreach($_POST['ticket'] as $key=>$post) {
                if(!isset($_REQUEST['pid'])){
                    $cr = $tobj->AddPrice($res['pid'], $post,0, $soap,$pft_rflex_id, $soap2,$res['sync_id'], $res['sync_status']);
                    $cr == 100 ? $cre_inc += 1 : $cre_res[] = $SoapRequestChk[$cr].$cr;
                    continue;
                }
                if($key<=0) {
                    //create
                    $cr = $tobj->AddPrice($res['pid'], $post,0, $soap,
                        $pft_rflex_id, $soap2,$res['sync_id'], $res['sync_status']);
                    //echo $cr;
                    $cr == 100 ? $cre_inc += 1 : $cre_res[] = $SoapRequestChk[$cr].$cr;
                }
                elseif($key>0) {
                    if(count($package)){
                        // 找出子票的时间段日历价格
                        $xml = $Price->GetDynamicPrice('', 1, $post['bt'], $post['et'], 0, 0, $_REQUEST['pid']);
                        $sx = simplexml_load_string($xml);
                        // 找出套票的时间段日历价格(每个套票一个数组)
                        $packs = array();
                        $nums = array();
                        foreach($package as $pv => $tsa){// 会找出重复
                            $tmpXml = $Price->GetDynamicPrice('', 1, $post['bt'], $post['et'], 0, 0, $pv);
                            $tmpSx = simplexml_load_string($tmpXml);
                            if(empty($tmpSx)) continue;
                            $packs[$pv]=$tmpSx;
                            $tp = explode('|',$tsa);
                            $nums[$pv] = $tp[1] ;
                        }
                    }
                    //update
                    $ur = $tobj->AddPrice($res['pid'], $post,$key, $soap,
                        $pft_rflex_id, $soap2,$res['sync_id'], $res['sync_status']);
                    if($ur == 100){    // 修改成功后找到该子票打包的套票
                        $area = true;
                        if((strtotime($post['et']) - strtotime($post['bt']))==0){// 更改子票时间段时，时间段内如果有单独配置，配置是不生效的
                            $area = false;
                        }
                        // 处理
                        if(count($sx->Rec)){
                            foreach($sx->Rec as $val){
                                if((strtotime((string)$val->UUstart_date) - strtotime((string)$val->UUend_date))==0 && $area)continue;// 配置一天的
                                // 子票原售价
                                $sPs = (string)$val->UUs_price ? (string)$val->UUs_price:(string)$val->UUn_price;// 供货价
                                $sPl = (string)$val->UUl_price;// 零售价
                                $diffPs = $post['pg'] - $sPs/100;
                                $diffPl = $post['pl'] - $sPl/100;

                                // 每个套票
                                foreach($packs as $pv){
                                    // 每个时间数组
                                    foreach($pv as $dk => $de){
                                        //     配置一天的
                                        if((strtotime((string)$de->UUstart_date) - strtotime((string)$de->UUend_date))==0 && $area)continue;
                                        if(((string)$val->UUstart_date==(string)$de->UUstart_date)&&((string)$val->UUend_date==(string)$de->UUend_date) || ((string)$de->UUstart_date>=(string)$val->UUstart_date)&&((string)$val->UUend_date>=(string)$de->UUend_date)){// 时间段相同就设置价格或者区间内

                                            if($diffPs>0){// 增加
                                                // 套票原日期价格
                                                $packPris = (string)$de->UUs_price ? (string)$de->UUs_price:(string)$de->UUn_price;// 供货价
                                                $packPril = (string)$de->UUl_price;// 零售价
                                                $packPris = $packPris + $diffPs*100*$nums[(string)$de->UUpid];
                                                $packPril = $packPril + $diffPl*100*$nums[(string)$de->UUpid];;

                                                $hasMd[] = (string)$de->UUpid;// 有修改的后面通知供应商
                                                // 间隔区间内则应该是没有记录的
                                                $rid = (string)$de->UUid;
                                                Price::DynamicPriceStatic((string)$de->UUpid, (string)$de->UUstart_date,(string)$de->UUend_date, $packPris, $packPril, (string)$de->UUptype,$rid, (string)$de->UUmemo, (string)$de->UUweekdays, $soap, (string)$de->UUstorage);
                                                // );
                                            }
                                        }

                                    }
                                }
                            }
                        }
                    }
                    $ur == 100 ? $upt_inc +=1 : $upt_res[] = $SoapRequestChk[$ur].$ur;
                }
            }//EOF FOREACH

            if(count($hasMd)){// 发送平台信息通知
                include_once '../class/notice.class.php';
                include_once '../class/MemberAccount.class.php';
                $notice = new pft\notice();
                $ids = implode(',',$hasMd).','.abs($_REQUEST['pid']);
                $sql="SELECT p_name,apply_did,id FROM uu_products WHERE id IN ($ids)";
                $GLOBALS['le']->query($sql);
                $pinfo = array();
                while($row=$GLOBALS['le']->fetch_assoc()){
                    $pinfo[$row['id']]=$row;
                }
                foreach($pinfo as $k => $v){
                    if($k==abs($_REQUEST['pid'])) continue;
                    $packName = $v['p_name'];
                    $sonName = $pinfo[abs($_REQUEST['pid'])]['p_name'];
                    $msg = "您的套票产品【{$packName}】由于子票【{$sonName}】价格上调，系统自动上调套票价格，如果不想调整，请自行设置";
                    // echo "AddNotice('套票价格上调', $msg, 1, 9999, 1, 0, '', '',MemberAccount(le, {$v['apply_did']},),    {$v['apply_did']})";

                    $notice->AddNotice('套票价格上调', $msg, 1, 9999, 1, 0, '', '',
                        new \pft\Member\MemberAccount($GLOBALS['le'], $v['apply_did'], $s),
                        $v['apply_did']
                    );
                }
            }

            $cr_fail = count($cre_res);
            $ut_fail = count($upt_res);
            $pri_msg = "<br/>添加价格配置成功<span class='red'>{$cre_inc}</span>条，"
                ."失败<span class='red'>{$cr_fail}</span>条;<br/>";
            $pri_msg .= $cr_fail>0 ? "失败原因分别为:".implode(';',$cre_res).'<br/>':'';
            $pri_msg .= "更新价格配置<span class='red'>{$upt_inc}</span>条，".
                "失败<span class='red'>{$ut_fail}</span>条;<br/>";
            $pri_msg .= $ut_fail >0 ? "失败原因分别为:".implode(';',$upt_res).'<br/>':'';
            $res['msg'] .= $pri_msg;
        }
        //print_r($res);
        // 检测是否有套票，有套票并且各关联子票有冲突，下架套票
        // $msg = chkPackage($res['pid'],$GLOBALS['le']);

        $msg = chkPackage_new($res['pid']);

        if (!$tid) {
            //TODO::判定是否为同步产品
            $sql = "SELECT sync_id,sync_status,apply_did FROM uu_land WHERE id={$lid} LIMIT 1";
//            echo $sql;
            $GLOBALS['le']->query($sql);
            $sync_data = $GLOBALS['le']->fetch_assoc();
            if ( $sync_data['sync_status']==1 && $sync_data['sync_id'] ) {
                \Sync::Notify(array(
                    'action'    =>'create_ticket',
                    'sync_id'   => $sync_data['sync_id'],
                    'lid'       => $lid,
                    'tid'       => $res['lastid'],
                    'mid'       => $sync_data['apply_did'],
                ));
            }
        }
        //
        if(count($msg)){
            foreach($msg as $k=>$v){
                $prod->SetSceneryState(substr($k,2),2,'系统下架');
            }
        }
        // 重新生成静态文件
        $ptype = $_POST['ptype'];
        file_get_contents("http://www.12301.cc/module/link_product/save_link_products.php?token=cgp&lid=$lid&p_type=$ptype");
        // if(isset($_REQUEST['pid'])) Meituan_detect($_REQUEST['pid']+0, 2);


        // 有效期文本
        if(count($p_info)){// 已经发布的才有更改
            $_POST['delaydays'] = $_REQUEST['delaydays'] = ($_POST['validTime'] == 1 || $_POST['validTime'] ==2) ? abs($_POST['vt']):0;
            if($_POST['validTime']==1) $_POST['delaytype'] = 0;
            if($_POST['validTime']==2) $_POST['delaytype'] = 1;
            $_REQUEST['validHtml_1'] = htmlValid($p_info);
            $_REQUEST['validHtml_2'] = htmlValid($_POST);
        }


        $_REQUEST['pid']        = $res['pid'];
        $_REQUEST['add_ticket'] = ($tid==0) ? 1:0;
        fsock_no_wait_post("http://www.12301.cc/call/detect_prod.php", $_REQUEST);

        Response(json_encode($res));
        break;

    //产品状态设置
    case 'SetSceneryState':
        $id = $_POST['lid'];//数组或数字
        $state = abs($_POST['state']);
        $operid = isset($_SESSION['memberID'])?
            $_SESSION['memberID']: exit('{"msg":"您还未登录或登录超时，请刷新页面后重新登录"}') ;
        $res = $prod->SetSceneryState($id,$state,'分销商ID='.$operid);
        // 以下检测是否有打包的套票，有则一起下架
        if($state == 2 || $state == 3 ){
            $sql="SELECT p.id FROM uu_products p LEFT JOIN uu_jq_ticket t ON p.id=t.pid WHERE t.landid=$id AND p.p_status<6";
            $GLOBALS['le']->query($sql);
            $package = array();
            while($row=$GLOBALS['le']->fetch_assoc()){
                $package = array_merge($package,getMainId($row['id']));// 获取该门票被打包的景区ID
            }
            $package = array_unique($package);
            if(count($package)){
                $sql="SELECT id FROM uu_land WHERE status=1 AND id IN (".implode(',',$package).")";
                $package = array();
                $GLOBALS['le']->query($sql);
                while($row=$GLOBALS['le']->fetch_assoc()){
                    $prod->SetSceneryState($row['id'],2,'系统下架');
                    $stateMsg['S:'.$row['id']] = array(
                        'timer'=>date('Y年m月d日 H:i:s'),
                        'message'=>'套票关联子票被下架或删除，系统自动下架该套票',
                    );
                    buildMess($stateMsg);
                }
            }
        }
        fsock_no_wait_post("http://www.12301.cc/call/detect_prod.php", $_REQUEST);
        Response($res);
        break;
    //产品审核
    case 'SetVerifyStatus':
        $id     = intval($_POST['id']);//数字
        $state  = abs($_POST['state']);
        if ($_SESSION['sid']==1) {
            $res = $prod->SetVerifyStatus($id,$state);
            echo $res;
        } else {
            Response('{"status":"fail","msg":"您还未登录或登录超时，请刷新页面后重新登录"}') ;
        }
        fsock_no_wait_post("http://www.12301.cc/call/detect_prod.php", $_REQUEST);
        Response('');
        break;
    // 设置套票景区上架
    case 'SetPackState':
        include_once '/var/www/html/new/d/class/PackTicket.class.php';
        $id = $_POST['lid'];//数组或数字
        $pack = new PackTicket($id);
        $effective = $pack->checkEffectivePack();
        $state = abs($_POST['state']);
        if(!isset($_SESSION['memberID'])){
            echo '{"msg":"您还未登录或登录超时，请刷新页面后重新登录"}';
            break;
        }
        $operid = $_SESSION['memberID'];
        $res = $effective ? $prod->SetSceneryState($id,$state,'分销商ID='.$operid):1001;
        fsock_no_wait_post("http://www.12301.cc/call/detect_prod.php", $_REQUEST);
        Response($res);
        break;
    case 'SetProdStatus':
        //票类上下架
        $ids = rtrim($_POST['ids'],',');
        $status = abs($_POST['status']);
        $operid = $_SESSION['memberID'];
        $result = $prod->SetTicketStatus($status,$ids,$operid);
        if($result['status']=='ok'){



            $idArr = explode(',',$ids);
            // if($status==1){// 美团上下架
            // foreach($idArr as $k=>$ct) Meituan_detect($ct, 1);
            // }

            if($status == 2 || $status == 3 ){

                foreach($idArr as $k=>$ct){

                    // Meituan_detect($ct, 0);


                    $package = array();
                    $package = getMainId($ct);// 获取该门票被打包的景区ID
                    $package = array_unique($package);
                    if(count($package)){
                        $sql="SELECT id FROM uu_land WHERE status=1 AND id IN (".implode(',',$package).")";
                        $package = array();
                        $GLOBALS['le']->query($sql);
                        while($row=$GLOBALS['le']->fetch_assoc()){
                            $prod->SetSceneryState($row['id'],2,'系统下架');
                            $stateMsg['S:'.$row['id']] = array(
                                'timer'=>date('Y年m月d日 H:i:s'),
                                'message'=>'套票关联子票被下架或删除，系统自动下架该套票',
                            );
                            buildMess($stateMsg);
                        }
                    }
                }
            }
        }
        fsock_no_wait_post("http://www.12301.cc/call/detect_prod.php", $_REQUEST);
        Response(json_encode($result));
        break;
    case 'EditNotifyPhonenum':
        $landid   = (int)$_POST['lastid'];
        $phonenum = $_POST['phonenum'];
        if(!ismobile($phonenum)){
            Response('不正确的手机号码');
        }
        //TODO::判断同步
        $sqlChk = "SELECT sync_id,fax,apply_did FROM uu_land WHERE id={$landid} AND sync_status=1 LIMIT 1";
        $GLOBALS['le']->query($sqlChk);
//        echo $sqlChk;
        if ($r=$GLOBALS['le']->fetch_assoc()) {
//            print_r($r);
            $dbArr = \Sync::GetMulDB();
            $sync_id = $GLOBALS['le']->f('sync_id');
            $sync_fax = $GLOBALS['le']->f('fax');
            \Sync::LogSync('uu_land', $landid, $sync_id, array('diff_columns'=>'fax'),array('diff_columns'=>'fax'), $dbArr['trans_le']);
            \Sync::Notify(array(
                'action'=>'update_land',
                'lid'   => $landid,
                'mid'   => $GLOBALS['le']->f('apply_did'),
            ));
        }

        $str = "UPDATE uu_land SET fax='{$phonenum}' WHERE id={$landid} LIMIT 1";
        $GLOBALS['le']->query($str);
        Response('ok');
        break;
    case 'GetTickets':
        $ticket = new Ticket($GLOBALS['le']);
        $landid = abs($_GET['lid']);
        $status = 0;
        $priceFlag = isset($_GET['flag']) && $_GET['flag']=='all' ? 0 : 1;
        $output = $ticket->GetTicketByLimit($landid, $applydid, $status, $priceFlag,$soap);
        Response(json_encode($output));
        break;
    // 根据景区获取供应商可销售门票
    case 'GetSaleTicket':
        $sales = $member->salePros($_REQUEST['lid']);
        $reqArr = array();
        // print_r($sales);
        foreach($sales as $k=>$v){
            if($v['sapply_did']!=$_REQUEST['aid']) continue;
            $tmp = array();
            $tmp['prodid'] = $v['pid'];
            $tmp['ticketTitle'] = $v['ttitle'];
            $tmp['marketPrice'] = $v['tprice'];
            $tmp['salePrice'] = 0;
            $tmp['setlPrice'] = 0;
            $tmp['validDays'] = $v['delaydays'];
            $tmp['landid'] = $_REQUEST['lid'];
            $tmp['status'] = $v['status'];
            $reqArr[] = $tmp;
        }
        Response(json_encode($reqArr));
        break;

    case 'FindSalers':
        $sname = safetxt($_GET['sname']);
        $list = $mem->GetSalerList($sname);
        echo json_encode($list);
        break;
    case 'CountSale':
        //统计票类中销量
        $tid = intval($_GET['tid']);
        if($tid>0){
            $ticket = new Ticket($GLOBALS['le']);
            $c = $ticket->CountTicketSale($tid, $soap);
            $s = explode(',', $c);
            echo $s[1];
        }
        break;
    case 'ProdEvolute':
        //产品二手供应
        $pid = $_POST['pid'];
        $dtype = intval($_POST['dtype']);//0取消选择1更改选择或新增
        list($apply_did, $aids, $eid, $sapply_did) = explode('|', $_POST['info']);


        //判断是否可以购买此供应商下的产品
//        $str="select pids from pft_product_sale_list where fid={$_SESSION['memberID']} and aid=$apply_did and status=0 limit 1";
//        $GLOBALS['le']->query($str);
//        $GLOBALS['le']->fetch_assoc();
//        $pids=$GLOBALS['le']->f('pids');
//        if ($pids!='A'){
//            $a_pids=explode(',',$pids);
//            if (!in_array($pid,$a_pids)) {
//                echo "<script>alert('您已无权购买此产品，配置失败！');</script>";
//                exit;
//            }
//        }

        $sql_update = "UPDATE pft_p_apply_evolute SET active=0 WHERE pid=$pid".
            " AND fid={$_SESSION['sid']} AND active=1 LIMIT 1";
        $GLOBALS['le']->query($sql_update);
        if( !$dtype ) {
            //删除该产品下级分销商的供应数据
            $sql_hanler = "DELETE FROM pft_p_apply_evolute WHERE sid={$_SESSION['sid']} AND pid=$pid";
            $GLOBALS['le']->query($sql_hanler);
            Response('{"status":"ok","msg":"操作成功！","active":0}');
        }
        if( ! $eid ) {
            $sql_hanler = "INSERT INTO pft_p_apply_evolute(fid,sid,sourceid,pid,".
                "lvl,status,rectime,aids,active) VALUES({$_SESSION['sid']}, $apply_did".
                ",$apply_did,$pid,1,0,now(),$apply_did,1)";
        }
        else {
            //更新该记录为活动状态
            $GLOBALS['le']->query("UPDATE pft_p_apply_evolute SET active=1 WHERE id=$eid LIMIT 1");
            //删除该产品下级分销商的供应数据
            $sql_hanler = "DELETE FROM pft_p_apply_evolute WHERE sid={$_SESSION['sid']} AND pid=$pid";
        }
        $GLOBALS['le']->query($sql_hanler);

        if($_SESSION['alliance']){// 分销联盟给联盟成员配置产品
            Alliance::setEvoluteList($pid,$sapply_did);
        }
        Response('{"status":"ok","msg":"操作成功！","active":1}');
        break;
    case 'CheckOrderPay':
        $orderid = trim($_GET['orderid']);
        include("../class/OrderRecord.php");
        $order = new OrderRecord($orderid, $soap);
        $orderDetail = $order->info();
        if($orderDetail['mainOrder']->UUpmode==1
            &&$orderDetail['mainOrder']->UUpaystatus!=1) {
            exit('0');
        } else {
            echo('1');
        }
        break;
    case 'PriceRemove':
        $prcid = abs($_GET['prcid']);
        $pobj = new Price($pid);
        echo $pobj->RemoveSPrice($prcid);
        break;
    case 'OrderRelationShip':
        if ($_SESSION['sid']!=1) {
            exit('{"status":"fail","msg":"权限不够"}');
        }
        $ordernum = safetxt($_GET['ordernum']);
        $str=<<<SQL
SELECT d.orderid, d.series, d.assembly, d.memo, d.origin, d.concat_id,
d.pay_status, d.aids_money, d.aids, d.aids_price FROM uu_order_fx_details AS d
WHERE d.orderid='{$ordernum}' LIMIT 1
SQL;

        $GLOBALS['le']->query($str);
        $appendInfo=$GLOBALS['le']->fetch_assoc();
        if (!empty($appendInfo['aids_money'])) {
            $out = '';
            $sql = "SELECT dname,id FROM pft_member WHERE id IN({$appendInfo['aids']})";
            $GLOBALS['le']->query($sql);
            while($tmp = $GLOBALS['le']->fetch_assoc()) {
                $dnames[$tmp['id']] = $tmp['dname'];
            }
            $aids_money = array_reverse(unserialize($appendInfo['aids_money']));
            foreach ($aids_money as $row) {
                $ac = $row[2] == 0 ? '<span>(-)</span>':'(+)';
                $pt = $row[1]==1? '余额':'授信';
                $out .= $dnames[$row[0]] . ''.$pt . $ac ;
            }
            echo '{"status":"ok","msg":"","ret":"'.$out.'"}';
        } else {
            echo '{"status":"fail","msg":"没有多级分销"}';
        }
        break;
    /* 今天翻进来这里已经是被注释的状态了 待删 2015-06-12 zax
    case 'config_confirm_wx'://检查是否关注微信号 票类编辑里面使用
       $sel_wx = "select fromusername from uu_wx_member_pft where fid={$_SESSION['sid']} and aid=21207 limit 1";
       $le->query($sel_wx);
       $row = $le->fetch_assoc();
       if(!$row){
            echo '{"code":107,"msg":"未绑定微信公众号"}';
       }
       break;
    */
    case 'admin_land_search'://管理员身份全栈搜索景区名
        if($_SESSION['sid'] != 1)
            exit('{"status":"fail","msg":"身份错误"}');
        $title = mysql_real_escape_string($_REQUEST['ltitle']);
        $sql = "select id,title,salerid from uu_land where instr(title,'$title') order by id desc limit 10";
        $GLOBALS['le']->query($sql);
        while($row=$GLOBALS['le']->fetch_assoc()){
            $r['list'][] = $row;
        }
        $r['status'] = 'suc';
        exit(json_encode($r));
        break;
    case 'terminal_merge_search'://
        if($_SESSION['sid'] != 1)
            exit('{"status":"fail","msg":"身份错误"}');
        $title = mysql_real_escape_string($_REQUEST['ltitle']);
        $lid        = intval($_GET['lid']);
        $salerid    = intval($_GET['salerid']);
        $step       = intval($_GET['state']);
        if ($step==1) {
            //已合并的景区
            $sql_step1 = "SELECT nowSalerID FROM pft_terminal_share WHERE preSalerID=$salerid LIMIT 1";
            $GLOBALS['le']->query($sql_step1);
            $GLOBALS['le']->fetch_assoc();
            $mainNowSalerID = $GLOBALS['le']->f('nowSalerID');
            if ($mainNowSalerID) {
                $sql_merged = <<<SQL
SELECT l.id,l.title,s.nowSalerID as salerid FROM pft_terminal_share s
LEFT JOIN uu_land l ON l.salerid=s.preSalerID WHERE s.nowSalerID=$mainNowSalerID
SQL;
                $GLOBALS['le']->query($sql_merged);
                $merged_list = $list = array();
                while($row=$GLOBALS['le']->fetch_assoc()){
                    $list[] = $row;
                }
            }
        }
        elseif ($step==2) {
            //查询
            $sql = <<<SQL
SELECT id,title,salerid FROM uu_land
where instr(title,'$title') AND salerid<>$salerid AND p_type<>'F'
AND salerid not in (SELECT preSalerID FROM pft_terminal_share)
order by id desc
SQL;
//            echo $sql;
            $GLOBALS['le']->query($sql);
            while($row=$GLOBALS['le']->fetch_assoc()){
                $list[] = $row;
            }
        }
        $r['list']        = $list;
        $r['status']      = 'ok';
        exit(json_encode($r));
        break;
    case 'terminal_merge':
        if (!$_SESSION['memberID']) exit('{"status":"fail","msg":"未登录！"}');
        $main_id    = intval($_POST['main_id']);
        $merge_id   = $_POST['merge_id'];
        if (!$main_id || !$merge_id) {
            exit('{"status":"fail","msg":"参数错误"}');
        }
        $list           = array();
        $insert_values  = '';
        $merge_id = is_array($_POST['merge_id']) ? implode(',', $_POST['merge_id']) : $merge_id;
        $sql = "SELECT title,terminal,salerid,p_type FROM uu_land WHERE id=$main_id LIMIT 1";
        $GLOBALS['le']->query($sql);
        $list = $GLOBALS['le']->fetch_assoc();
        if ($list['p_type']=='F') {
            exit('{"status":"fail","msg":"套票无法合并终端"}');
        }
        //判断是否被合并的记录已存在
        $sql_main_merged = "SELECT nowSalerID FROM pft_terminal_share WHERE preSalerID={$list['salerid']} LIMIT 1";
        $GLOBALS['le']->query($sql_main_merged);
        $list_main_merged = $GLOBALS['le']->fetch_assoc();
        if (!$list_main_merged) {
            //统一处理新的salerid
//            $sql_main_salerid = "SELECT max(nowSalerID) as max FROM pft_terminal_share";
//            $GLOBALS['le']->query($sql_main_salerid);
//            $GLOBALS['le']->fetch_assoc();
//            $nowSalerID = $GLOBALS['le']->f('max');
//            $nowSalerID = $nowSalerID ? $nowSalerID + 1 : 10000001;

            $memParams = array(
                'dname'    => $list['title'].'-终端合并',
                'dtype'    => 3,//终端合并后的直接供应方
                'password' => 'b81b84c7961ac41a9e619458511a98d9',//md5(md5('uu654321'))
            );
            //生成直接供应商
            $reg_res = $mem->register($memParams, array());
            if($reg_res['status']=='ok') {
                $res_account = explode('|', $reg_res['body']);
                $nowSalerID  = $res_account[1];
                $insert_values .= <<<SQL
        ({$list['terminal']},{$list['terminal']},{$list['salerid']},
        {$nowSalerID}, 1, now(),'',{$_SESSION['memberID']}),
SQL;
            } else {
                print_r($reg_res);
            }
        }
        else {
            $nowSalerID = $list_main_merged['nowSalerID'];
        }
//        echo $insert_values;
//        exit;
        //查询需要合并的旧的记录
        $sql = <<<SQL
SELECT id,terminal,salerid FROM uu_land WHERE id IN($merge_id)
AND salerid not in (SELECT preSalerID FROM pft_terminal_share)
SQL;
        $GLOBALS['le']->query($sql);

        while($row = $GLOBALS['le']->fetch_assoc()) {
            $insert_values .= <<<SQL
        ({$row['terminal']},{$list['terminal']},{$row['salerid']},
        {$nowSalerID}, 0,now(),'',{$_SESSION['memberID']}),
SQL;
        }
        if (empty($insert_values)) {
            Response('{"status":"fail","msg":"数据不存在"}');
        }
        $insert_values = rtrim($insert_values, ',');
        $sql_insert = <<<SQL
INSERT INTO pft_terminal_share(preTerminal,nowTerminal,preSalerID,nowSalerID,
dstatus,addtime,verify_time,privID) VALUES $insert_values
SQL;
        $GLOBALS['le']->query($sql_insert);
        Response('{"status":"ok"}');
        break;
    // 获取分终端列表
    case 'sub_terminal_list':
        $memberSID = $_SESSION['sid'];
        $terminal = $_REQUEST['terminal'] + 0;
        if($terminal==0) Response('{"status":"fail","msg":"参数错误"}');
        $sql = "select id,preTerminal,nowSalerID from pft_terminal_share where nowTerminal=$terminal and privID=$memberSID";
        if($memberSID==1) $sql = "select id,preTerminal,nowSalerID from pft_terminal_share where nowTerminal=$terminal";
        $GLOBALS['le']->query($sql);
        while($row = $GLOBALS['le']->fetch_assoc()) $tlist[] = $row;
        Response(json_encode(array('status'=>'success','list'=>$tlist)));
        break;
    // 添加分终端
    case 'sub_terminal_add':

        $landid   = $_REQUEST['landid'] + 0;
        $sub_tnum = $_REQUEST['num'] + 0;
        $terminal = $_REQUEST['terminal'] + 0;

        $params = array();
        $params['mid']       = $_SESSION['sid'];
        $params['action']    = 'TERMINAL_DIVIDE';
        $params['main_id']   = $landid;
        $params['merge_num'] = 1;

        ksort($params);
        $auth = md5(implode(',', $params));
        $params['auth'] = $auth;
        $clsResult = file_get_contents('http://10.117.7.197/new/d/api/terminal_merge.php?'.http_build_query($params));
        $resResult = json_decode($clsResult, true);
        if($resResult['status']=='ok') Response(json_encode(array('status'=>'success','list'=>$resResult['terminals'])));
        Response('{"status":"fail","msg":"其他错误，请重试"}');
        break;
    default:
        break;
}
@$GLOBALS['le']->close();
exit;

function Meituan_detect($pid, $status){

    $MTID = 28227;
    $sql = "select landid as lid,apply_did,id as tid from uu_jq_ticket where pid=$pid limit 1";
    $GLOBALS['le']->query($sql);
    $p_info = $GLOBALS['le']->fetch_assoc();
    $tplStr_s = $p_info['lid'].'|'.$p_info['tid'];// 供应商ID|lid|tid


    $tplStr_a = array();// 转分销
    $sql = "select sid from pft_p_apply_evolute where pid=$pid and fid=$MTID and status=0";
    $GLOBALS['le']->query($sql);
    while($row=$GLOBALS['le']->fetch_assoc()) $tplStr_a[$row['sid'].'|'.$tplStr_s] = $row['sid'];

    $tplStr_a[$p_info['apply_did'].'|'.$tplStr_s] = $p_info['apply_did'];
    foreach($tplStr_a as $tid_aid=>$supplier){
        $sql = "select id from uu_qunar_use where fid=$supplier and DockingMode=1 and tid_aid='$tid_aid' limit 1";
        $GLOBALS['le']->query($sql);
        if($GLOBALS['le']->fetch_assoc())
            file_get_contents('http://10.160.4.140/new/d/meituan/MT_ChangeNotice.php?ids='.$tid_aid.'&status='.$status);
    }

}

function write_logs($txt,$file=''){
    if($file=='') $file = '/var/www/html/new/d/logs/cache_logs/BeforeModifyPros/uu_jq_ticket_'.date('Ymd').'.txt';
    $fp = fopen($file,"a");
    flock($fp, LOCK_EX);
    fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}
function fsock_no_wait_post($url, $data){
    $pams = trim(http_build_query($data));
    $lens = strlen($pams);
    $info = parse_url($url);
    $fp   = fsockopen($info["host"], 80, $errno, $errstr, 8);
    $qury = isset($info["query"]) ? $info["query"]:'';
    $head = "POST ".$info['path']."?".$qury." HTTP/1.0\r\n";
    $head.= "Host: ".$info['host']."\r\n";
    $head.= "Referer: http://".$info['host'].$info['path']."\r\n";
    $head.= "Content-type: application/x-www-form-urlencoded\r\n";
    $head.= "Content-Length: ".$lens."\r\n";
    $head.= "\r\n";
    $head.= $pams;
    $write = fputs($fp, $head);
}

function htmlValid($p_info){

    if($p_info['delaydays']>0){
        if($p_info['delaytype']==0) $valid = '游玩日期(含)'.$p_info['delaydays'].'天内有效';
        if($p_info['delaytype']==1) $valid = '下单日期(含)'.$p_info['delaydays'].'天内有效';
    }
    if($p_info['order_start']=='' && $p_info['delaydays'] == 0) $valid = '订单当天有效';

    if($p_info['order_start']!='' && $p_info['order_end']!='' ){
        $valid = date('Y-m-d', strtotime($p_info['order_start'])).' 至 '.date('Y-m-d', strtotime($p_info['order_end']));
    }elseif($p_info['order_start']=='' && $p_info['order_end']!=''){
        $valid = '截止'.$p_info['order_end'];
    }
    return $valid;
}

function Response($text){
    $GLOBALS['le']->close();
    exit("$text");
}
